﻿using FCT551.Base;
using FCT551.Models;
using FCT551.Views;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media.Imaging;
using FCT551.Helper;
using Common;

namespace FCT551.ViewModels
{
    public class IODebugViewModel : NotifyPorperChanged
    {
        private IODebugView _ioDebugView;
        public static CancellationTokenSource _cancellTask;
        private bool _isCommonIOChange = true;
        public static updateHandler updatemessage;

        public IODebugViewModel(IODebugView ioDebugView)
        {
            _ioDebugView = ioDebugView;
            DiDoCommonStatuses = new();
            WindowLoadedCommand = new Command() { ExeAction = new Action<object>(WindowLoadedCmd) };
            WindowClosingCommand = new Command() { ExeAction = new Action<object>(WindowClosingCmd) };
        }

        #region 绑定方法

        /// <summary>
        /// 节目退出方法
        /// </summary>
        /// <param name="obj"></param>
        private void WindowClosingCmd(object obj)
        {
            Global._isIOdebug = false;
            _cancellTask.Cancel();
        }

        /// <summary>
        /// 界面加载方法
        /// </summary>
        /// <param name="obj"></param>
        private void WindowLoadedCmd(object obj)
        {
            try
            {
                Global._isIOdebug = true;
                _cancellTask = new();
                DiDoCommonStatuses = new();

                foreach (var item in Global._IOconfigs)
                {
                    DiDoStatusModel diDoStatus = new DiDoStatusModel();
                    //默认都是前台修改
                    diDoStatus.IsbackGround = false;
                    diDoStatus.Channel = Convert.ToInt32(item.Value);
                    diDoStatus.DisplayText = item.Key + "[" + item.Value + "]";
                    diDoStatus.Status = false;

                    if (item.Key.Contains("DI"))
                    {
                        diDoStatus.IsDo = false;
                    }
                    else
                    {
                        diDoStatus.IsDo = true;
                    }
                    diDoStatus._action += DiDoCommonStatuseChanged;
                    if (diDoStatus.DisplayText.Contains("通用"))
                    {
                        diDoStatus.Type = DiDoType.Common;
                        DiDoCommonStatuses.Add(diDoStatus);
                    }
                }

                //轮询读取CommonIO
                Task.Run(async () =>
                {
                    try
                    {
                        Global._PqwIoCommon.GetDi();
                        Global._PqwIoCommon.GetDo();
                        for (int i = 0; i < DiDoCommonStatuses.Count; i++)
                        {
                            if (DiDoCommonStatuses[i].IsDo)
                            {
                                DiDoCommonStatuses[i].IsbackGround = true;
                                DiDoCommonStatuses[i].Status = Global._PqwIoCommon.GetDo(DiDoCommonStatuses[i].Channel);
                            }
                            else
                            {
                                DiDoCommonStatuses[i].IsbackGround = true;
                                DiDoCommonStatuses[i].Status = Global._PqwIoCommon.GetDi(DiDoCommonStatuses[i].Channel);
                            }
                        }
                        await Task.Delay(1000);
                        while (!_cancellTask.IsCancellationRequested)
                        {
                            try
                            {
                                _isCommonIOChange = true;
                                Global._PqwIoCommon.GetDi();
                                for (int i = 0; i < DiDoCommonStatuses.Count; i++)
                                {
                                    if (!DiDoCommonStatuses[i].IsDo)
                                    {
                                        DiDoCommonStatuses[i].IsbackGround = true;
                                        DiDoCommonStatuses[i].Status = Global._PqwIoCommon.GetDi(DiDoCommonStatuses[i].Channel);
                                    }
                                }

                                _isCommonIOChange = false;
                                await Task.Delay(500);
                            }
                            catch (Exception e)
                            {
                                UpdateMessage(e.Message, LogLevel.Error);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        UpdateMessage(e.Message, LogLevel.Error);
                    }
                    //实时读取
                }, _cancellTask.Token);
            }
            catch (Exception e)
            {
                UpdateMessage(e.Message, LogLevel.Error);
            }
        }

        #endregion 绑定方法

        #region 初始化绑定属性和命令

        //private ObservableCollection<DiDoStatusModel> _diDoCommonStatuses;
        private ObservableCollection<DiDoStatusModel> _diDoCommonStatuses;

        /// <summary>
        /// 通用IO
        /// </summary>
        public ObservableCollection<DiDoStatusModel> DiDoCommonStatuses
        {
            set
            {
                _diDoCommonStatuses = value;
                this.SetProperty();
            }
            get
            {
                return _diDoCommonStatuses;
            }
        }

        private Command _windowLoadedCommand;

        public Command WindowLoadedCommand
        {
            set
            {
                _windowLoadedCommand = value;
            }
            get
            {
                return _windowLoadedCommand;
            }
        }

        private Command _windowClosingCommand;

        public Command WindowClosingCommand
        {
            set
            {
                _windowClosingCommand = value;
            }
            get
            {
                return _windowClosingCommand;
            }
        }

        #endregion 初始化绑定属性和命令

        #region 普通方法

        /// <summary>
        /// IO写入方法
        /// </summary>
        private void DiDoCommonStatuseChanged(DiDoStatusModel obj, bool value)
        {
            int index = obj.Channel;

            switch (obj.Type)
            {
                case DiDoType.Common:
                    //if (!_isCommonIOChange)
                    //{
                    Global._PqwIoCommon.SetDo(index, value);
                    Global._PqwIoCommon.GetDo();
                    DiDoCommonStatuses[index + 11].IsbackGround = true;
                    DiDoCommonStatuses[index + 11].Status = Global._PqwIoCommon.GetDo(DiDoCommonStatuses[index + 11].Channel);
                    // }
                    break;
            }
        }

        private void UpdateMessage(string msg, LogLevel logLevel = LogLevel.Info)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                updatemessage?.Invoke(msg, logLevel);
            });
        }

        #endregion 普通方法
    }
}